package ynu.lcy.entity;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import org.hibernate.annotations.Where;
import ynu.lcy.dto.business.BusinessRequestDTO;
import ynu.lcy.elememicroservicecommon.entity.LogicEntity;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Entity
@Setter
@Getter
@NoArgsConstructor
@Where(clause = "is_deleted = 0")
@JsonIgnoreProperties(value = {"hibernateLazyInitializer", "handler", "fieldHandler"})
public class Business extends LogicEntity {

    /*
    * 商家推荐权重
    * */
    private Long businessWeight;
    /**
     * 商家名称
     **/
    private String businessName;
    /**
     * 商家地址
     **/
    private String businessAddress;
    /**
     * 商家描述
     **/
    private String businessExplain;
    /**
     * 商家图片
     **/
    private String businessImg;

    /**
     * 商家起送费
     **/
    private double starPrice;
    /**
     * 商家配送费
     **/
    private double deliveryPrice;

    /**
     * 所属类型
     * */
    @OneToMany(mappedBy = "business",
            fetch = FetchType.EAGER,
            orphanRemoval = true,
            cascade = CascadeType.ALL)
    @JsonIgnoreProperties(value = {"business"})
    @Fetch(FetchMode.SUBSELECT)
    private List<BusinessOrderType> businessOrderTypes;


    /**
     * 创建商家
     * @param businessImg
     * @param dto
     * @param orderTypes
     * @return
     * */
    @JsonIgnore
    public Business create(BusinessRequestDTO dto, String businessImg, List<OrderType> orderTypes){
        this.businessName = dto.getBusinessName();
        this.businessAddress = dto.getBusinessAddress();
        this.businessWeight =  dto.getBusinessWeight();
        this.businessExplain = dto.getBusinessExplain();
        this.businessImg = businessImg;
        this.createTime = new Date();
        this.starPrice = dto.getStarPrice();
        this.deliveryPrice = dto.getDeliveryPrice();
        //设置标签
        List<BusinessOrderType> businessOrderTypes = new ArrayList<>();
        orderTypes.forEach(orderType ->{
            BusinessOrderType businessOrderType = new BusinessOrderType();
            businessOrderType.setCreateTime(new Date());
            businessOrderType.setOrderType(orderType);
            businessOrderType.setBusiness(this);
            businessOrderTypes.add(businessOrderType);
        });

        this.businessOrderTypes = businessOrderTypes;
        return this;
    }

}
